import type { Response } from 'express'
import jwt from 'jsonwebtoken'
import type { RequestParams } from '../types'
import { userAuthenticationService } from '../service/userService'
import { sendResponseSync } from '../utils'
import logger from '../utils/logger'

export const userAuthenticationController = async function (req: RequestParams<{ code: string; type?: string }>, res: Response) {
  const jwtSecret = process.env.JWT_SECRET // 使用环境变量，如果没有则使用默认值
  const { code } = req.body
  try {
    const wxInfo = await userAuthenticationService(code)
    logger.info('wxInfo:', wxInfo)
    const token = jwt.sign({
      openid: wxInfo.openid,
    }, jwtSecret, { expiresIn: '48h' })
    logger.info(token)
    res.send(sendResponseSync({ data: { token, ...wxInfo } }))
  }
  catch (e) {
    logger.error(`${e}`)
    res.send(sendResponseSync({ type: 'Fail', message: e }))
  }
}
